<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { TClass } from '@/Types/education'
import GroupBarEchart from '@/components/Echart/groupBarEchart.vue'
import { getScoreListBySpecificService } from '@/api/education/score'
import { getUserListByClassIdListService } from '@/api/user_classname'
import { getSubjectBySpecificService } from '@/api/education/subject'
import { TScore } from '@/Types/score'
import { TSubject } from '@/Types/subject'
import { useRoute } from 'vue-router'
import { getClassnameByIdService } from '@/api/education/classname'
import { getScoreStatsListService } from '@/api/education/scoreStats'
import { exportScoreToExcel } from '@/components/Class/exportScore'
import router from '@/router'

const classList = ref<TClass[]>([])
const academicYears = ref(['2023-2024', '2022-2023', '2021-2022']) // 学年列表
const subjectIdList = ref<number[]>([])
const subjectList = ref<TSubject[]>([]) // 科目列表
const loading = ref(false)
const currentYear = ref('2023-2024') // 当前学年
const currentClass = ref<TClass>() // 当前班级
const currentSubject = ref('') // 当前科目
const currentExamType = ref<'theory' | 'practice'>('theory') // 当前考试类型：理论或实践
const isEnableSubjectSelect = ref(false) // 是否启用科目选择
const isEnableQuery = ref(true) // 是否启用查询

// 添加学生成绩数据类型
const studentScore = ref<
	{
		userId: number
		studentId: string
		name: string
		scores: {
			theory: {
				status?: string
				midTerm?: number
				final?: number
				usual?: number
				total?: number
			}
			practice: {
				status?: string
				midTerm?: number
				final?: number
				usual?: number
				total?: number
			}
		}
	}[]
>([])

// 添加一个存储所有成绩数据的变量
const allScoreData = ref<any[]>([])

// 添加统计数据的状态
const scoreStats = ref<
	{
		academyYear: string
		avgScorePractice: number
		avgScoreTheory: number
		classId: number
		excellentRatePractice: number
		excellentRateTheory: number
		maxScorePractice: number
		maxScoreTheory: number
		passRatePractice: number
		passRateTheory: number
		practiceTotalViolations: number
		theoryTotalViolations: number
		practiceTotalAbsences: number
		theoryTotalAbsences: number
		subjectId: number
		updateTimePractice: string
		updateTimeTheory: string
	}[]
>([])

/**
 * 获取当前科目的统计数据
 */
const getCurrentSubjectStats = computed(() => {
	if (!scoreStats.value.length || !currentSubject.value) return null

	return scoreStats.value.find((stat) => String(stat.subjectId) === currentSubject.value)
})

/**
 * 获取当前显示的统计数据项
 */
const statisticsItems = computed(() => {
	const stats = getCurrentSubjectStats.value
	if (!stats) return []

	const examType = currentExamType.value
	const items = [
		{
			label: '平均分',
			value:
				examType === 'theory'
					? stats.avgScoreTheory?.toFixed(1) || '0'
					: stats.avgScorePractice?.toFixed(1) || '0',
			color: '#409EFF'
		},
		{
			label: '最高分',
			value:
				examType === 'theory'
					? stats.maxScoreTheory?.toString() || '0'
					: stats.maxScorePractice?.toString() || '0',
			color: '#67C23A'
		}
	]

	return items
})

/**
 * 获取考试异常情况数据
 */
const examAbnormalStats = computed(() => {
	const stats = getCurrentSubjectStats.value
	if (!stats) return []

	const examType = currentExamType.value
	return [
		{
			label: '违规人数',
			value:
				examType === 'theory'
					? stats.theoryTotalViolations?.toString() || '0'
					: stats.practiceTotalViolations?.toString() || '0',
			color: '#F56C6C'
		},
		{
			label: '缺考人数',
			value:
				examType === 'theory'
					? stats.theoryTotalAbsences?.toString() || '0'
					: stats.practiceTotalAbsences?.toString() || '0',
			color: '#E6A23C'
		}
	]
})

/**
 * 模块名: 数据获取
 */
// 获取班级数据
const route = useRoute()
const classId = Number(route.params.classId)
const getClassInfo = async () => {
	try {
		if (classId !== null && classId !== undefined) {
			const condition = {
				academicYear: currentYear.value,
				classId: classId
			}
			await getSubjectInfo(condition)
			isEnableSubjectSelect.value = true
		}

		const res = await getClassnameByIdService(classId)
		if (res.data.code === 1) {
			currentClass.value = {
				...res.data.data,
				level:
					res.data.data.level === 'undergrad'
						? '本科'
						: res.data.data.level === 'vocEd'
							? '专科'
							: res.data.data.level
			}
		}

		await handleQuery()
		await getScoreStatsList()

		// 处理空科目列表
		handleEmptySubjects()
	} catch (error) {
		ElMessage.error('获取班级数据失败')
	}
}

// 获取科目信息
const getSubjectInfo = async (data: any) => {
	const res = await getScoreListBySpecificService(data)
	if (res.data.code === 1) {
		subjectIdList.value = res.data.data.map((item: TScore) => item.subjectId)
		const data = [...new Set(JSON.parse(JSON.stringify(subjectIdList.value)))]

		if (data.length === 0) {
			// 如果没有科目数据
			subjectList.value = []
			currentSubject.value = ''
			// console.log('当前学年没有科目数据')
			return
		}

		const result = await getSubjectBySpecificService(data)
		subjectList.value = result.data.data

		// console.log(result.data.data.length)
		// console.log(subjectList.value.length)
		// console.log(subjectList.value[0])
		// console.log(subjectList.value[0].id)
		// 设置默认科目 - 使用ID而不是名称
		if (subjectList.value.length > 0) {
			currentSubject.value = String(subjectList.value[0].id)
		}
	} else {
		ElMessage.error('获取科目信息失败')
	}
}

// 获取统计数据
const getScoreStatsList = async () => {
	const condition = {
		academyYear: currentYear.value,
		classId: currentClass.value?.classId
	}
	const res = await getScoreStatsListService(condition)
	if (res.data.code === 1) {
		scoreStats.value = res.data.data
		// console.log('获取统计数据成功:', res.data.data)
	}
}

// 获取学生信息
const getStudentInfo = async () => {
	try {
		if (!currentClass.value || !currentClass.value.classId) return
		const res = await getUserListByClassIdListService(1, [currentClass.value.classId])
		if (res.data.code === 1) {
			// 转换学生成绩的数据结构，不设置初始状态
			studentScore.value = res.data.data.map((student: any) => ({
				userId: student.userId,
				studentId: student.typeNumber,
				name: student.uname,
				scores: {
					theory: {},
					practice: {}
				}
			}))
		}
	} catch (error) {
		ElMessage.error('获取学生信息失败')
	}
}

// 获取成绩数据
const getClassScoreList = async () => {
	loading.value = true
	isEnableQuery.value = false

	const condition = {
		academicYear: currentYear.value,
		classId: currentClass.value?.classId
	}

	try {
		const res = await getScoreListBySpecificService(condition)
		if (res.data.code === 1) {
			// 存储所有成绩数据
			allScoreData.value = res.data.data

			// 清空当前显示的成绩数据
			studentScore.value.forEach((student) => {
				student.scores = {
					theory: {},
					practice: {}
				}
			})

			// 如果有默认科目且科目列表不为空，更新学生成绩显示
			if (currentSubject.value && subjectList.value.length > 0) {
				updateStudentScores(currentSubject.value)
			} else {
				// 如果没有科目数据，显示提示
				handleEmptySubjects()
			}
		}

		setTimeout(() => {
			isEnableQuery.value = true
			isEnableSubjectSelect.value = true
		}, 1000)
	} catch (error) {
		ElMessage.error('获取成绩数据失败')
	} finally {
		loading.value = false
	}
}

// 更新学生成绩显示
const updateStudentScores = (subjectId: string) => {
	if (!subjectId || !allScoreData.value.length) {
		return
	}

	// 检查科目是否存在
	const subjectExists = subjectList.value.some((s) => String(s.id) === subjectId)
	if (!subjectExists) {
		console.log('选中的科目不在当前科目列表中')
		return
	}

	// 根据选择的科目筛选成绩数据
	const filteredScores = allScoreData.value.filter(
		(score: any) => String(score.subjectId) === subjectId
	)

	// 更新学生成绩显示
	studentScore.value.forEach((student) => {
		const score = filteredScores.find((s: any) => s.studentId === student.userId)
		if (score) {
			student.scores = {
				theory: {
					status: score.aboutTheory || 'normal',
					midTerm: score.midTermTheory,
					final: score.finalTheory,
					usual: score.usualTheory,
					total: score.theoryTotal
				},
				practice: {
					status: score.aboutPractice || 'normal',
					midTerm: score.midTermPractice,
					final: score.finalPractice,
					usual: score.usualPractice,
					total: score.practiceTotal
				}
			}
		} else {
			// 如果没有找到对应成绩，保持空数据
			student.scores = {
				theory: {},
				practice: {}
			}
		}
	})
}

// 监听学年变化，更新数据
watch(currentYear, async (newYear) => {
	console.log('学年变更为:', newYear)
	try {
		// 清空科目数据，避免显示旧数据
		currentSubject.value = ''
		subjectList.value = []

		// 刷新科目数据
		const condition = {
			academicYear: newYear,
			classId: classId
		}
		await getSubjectInfo(condition)

		// 刷新成绩和统计数据
		await getClassScoreList()
		await getScoreStatsList()
	} catch (error) {
		ElMessage.error('学年变更后更新数据失败')
	}
})

// 处理空科目列表的情况
const handleEmptySubjects = () => {
	// 如果科目列表为空，显示提示
	if (subjectList.value.length === 0) {
		ElMessage.warning('当前学年没有科目数据')
		// 清空成绩数据
		studentScore.value.forEach((student) => {
			student.scores = {
				theory: {},
				practice: {}
			}
		})
	}
}

// 修改科目选择的监听器
watch(currentSubject, (newSubject) => {
	console.log('科目变更为:', newSubject)
	if (!newSubject) {
		// 如果没有选择科目，清空所有成绩显示
		studentScore.value.forEach((student) => {
			student.scores = {
				theory: {},
				practice: {}
			}
		})
		return
	}

	updateStudentScores(newSubject)
})

// 监听考试类型变化
watch(currentExamType, () => {
	// 当考试类型改变时，更新图表数据
	// 图表已经是计算属性，会自动更新
})

/**
 * 图表配置
 */
const groupBarChartData = computed(() => {
	if (!scoreStats.value.length || !subjectList.value.length) {
		return {
			subject: [],
			passRate: [],
			excellentRate: [],
			violationCount: [],
			title: ''
		}
	}

	const examType = currentExamType.value

	// 映射科目名称和ID的关系
	const subjectIdToName: Record<number, string> = {}
	subjectList.value.forEach((s) => {
		if (s.id !== undefined) {
			subjectIdToName[s.id] = s.subject || ''
		}
	})

	// 排序统计数据，确保与科目列表顺序一致
	const orderedStats: typeof scoreStats.value = []
	subjectList.value.forEach((subject) => {
		if (subject.id !== undefined) {
			const stat = scoreStats.value.find((s) => s.subjectId === subject.id)
			if (stat) {
				orderedStats.push(stat)
			}
		}
	})

	return {
		subject: subjectList.value.map((item) => item.subject || ''),
		passRate: orderedStats.map((stat) =>
			examType === 'theory' ? stat.passRateTheory : stat.passRatePractice
		),
		excellentRate: orderedStats.map((stat) =>
			examType === 'theory' ? stat.excellentRateTheory : stat.excellentRatePractice
		),
		violationCount: orderedStats.map((stat) =>
			examType === 'theory' ? stat.theoryTotalViolations : stat.practiceTotalViolations
		),
		title: `${examType === 'theory' ? '理论' : '实践'}成绩统计`
	}
})

/**
 * 数据格式化
 */
// 根据分数设置样式类名
const getScoreClass = (score: number) => {
	if (score >= 100) return 'score-all'
	if (score >= 80) return 'score-good'
	if (score >= 60) return 'score-medium'
	if (score >= 50) return 'score-pass'
	if (score >= 40) return 'score-fail'
	return 'score-fail'
}
// 设置考试状态显示文本
const setStatusText = (status: string) => {
	const statusMap = {
		normal: '正常',
		absent: '缺考',
		violation: '作弊'
	}
	return statusMap[status as keyof typeof statusMap] || '-'
}

// 设置考试状态显示样式
const setStatusStyle = (status: string) => {
	const classMap = {
		normal: 'status-normal',
		absent: 'status-absent',
		violation: 'status-violation'
	}
	return classMap[status as keyof typeof classMap] || ''
}

/**
 * 生命周期
 */
onMounted(async () => {
	await getClassInfo()
})

/**
 * 页面操作
 */
// 点击查询
const handleQuery = async () => {
	await getStudentInfo()
	await getClassScoreList()
}
// 导出成绩
const handleExport = () => {
	if (!currentSubject.value || !currentClass.value) {
		ElMessage.warning('请先选择班级和科目')
		return
	}

	if (subjectList.value.length === 0) {
		ElMessage.warning('请先选择科目')
		return
	}

	const subjectName =
		subjectList.value.find((s) => String(s.id) === currentSubject.value)?.subject || '未知科目'
	const className = `${currentYear.value}学年${currentClass.value?.academy || ''}${currentClass.value?.major || ''}${currentClass.value?.grade || ''}级${currentClass.value?.classname || '未知班级'}班`
	const fileName = `${className}${subjectName}`

	ElMessageBox.confirm(`确认导出${className}的${subjectName}成绩数据?`, '导出确认', {
		confirmButtonText: '确认导出',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			try {
				exportScoreToExcel(studentScore.value, fileName)
				ElMessage.success('导出成功')
			} catch (error) {
				console.error('导出失败:', error)
				ElMessage.error('导出失败')
			}
		})
		.catch(() => {
			ElMessage.info('已取消导出')
		})
}
// 返回班级管理
const handleBack = () => {
	router.back()
}
</script>

<template>
	<div class="score-manage">
		<el-card shadow="hover">
			<!-- 导航栏 -->
			<template #header>
				<div class="card-header">
					<div class="left-section">
						<el-button :icon="ArrowLeft" type="primary" @click="handleBack">返回</el-button>
						<el-divider direction="vertical" />
						<div class="class-info" v-show="currentClass">
							<span>{{ currentClass?.academy }}</span>
							<el-divider direction="vertical" />
							<span>{{ currentClass?.major }}</span>
							<el-divider direction="vertical" />
							<span>{{ currentClass?.grade }}</span>
							<el-divider direction="vertical" />
							<span>{{ currentClass?.classname }}</span>
						</div>
					</div>
					<div class="header-operations">
						<el-button @click="handleExport">导出成绩</el-button>
					</div>
				</div>
			</template>

			<!-- 顶部操作区域 -->
			<div class="operation-area">
				<div class="filter-section">
					<div class="selector-group">
						<div class="year-selector">
							<span class="label">学年：</span>
							<el-select v-model="currentYear" size="small" class="selector">
								<el-option v-for="year in academicYears" :key="year" :label="year" :value="year" />
							</el-select>
						</div>
						<div class="class-selector" v-show="classList.length > 0">
							<span class="label">班级：</span>
							<el-select v-model="currentClass" size="small" class="selector" style="width: 300px">
								<el-option
									v-for="c in classList"
									:key="c.classId"
									:value="c.classId"
									:label="c.classname"
								/>
							</el-select>
						</div>
						<div class="exam-type-selector">
							<span class="label">考试类型：</span>
							<el-select v-model="currentExamType" size="small" class="selector">
								<el-option label="理论" value="theory" />
								<el-option label="实践" value="practice" />
							</el-select>
						</div>
						<div class="subject-selector">
							<span class="label">科目：</span>
							<el-select
								v-model="currentSubject"
								:disabled="!isEnableSubjectSelect"
								size="small"
								class="selector"
							>
								<el-option
									v-for="s in subjectList"
									:key="s.id"
									:label="s.subject"
									:value="String(s.id)"
								/>
							</el-select>
						</div>
					</div>
				</div>
			</div>

			<!-- 成绩分布图表 -->
			<div class="chart-container">
				<GroupBarEchart :chart-data="groupBarChartData" />
			</div>

			<!-- 成绩表格和统计信息 -->
			<div class="data-container">
				<!-- 成绩表格 -->
				<div class="table-container">
					<el-table
						:data="studentScore"
						border
						height="320px"
						v-loading="loading"
						class="score-table"
						:empty-text="
							classList.length === 0
								? '请先选择班级'
								: studentScore.length === 0
									? '没有可用的科目数据'
									: '暂无成绩数据'
						"
					>
						<el-table-column type="index" label="序号" width="50" align="center" />
						<el-table-column prop="name" label="姓名" width="80" align="center" />
						<el-table-column prop="studentId" label="学号" width="140" align="center" sortable />

						<!-- 理论成绩部分 -->
						<el-table-column label="理论成绩" align="center">
							<el-table-column label="考试情况" width="100" align="center">
								<template #default="{ row }">
									<span :class="setStatusStyle(row.scores.theory.status)">
										{{ setStatusText(row.scores.theory.status) }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="期中" width="85" align="center">
								<template #default="{ row }">
									<span :class="getScoreClass(row.scores.theory.midTerm || 0)">
										{{ row.scores.theory.midTerm || '-' }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="期末" width="85" align="center">
								<template #default="{ row }">
									<span :class="getScoreClass(row.scores.theory.final || 0)">
										{{ row.scores.theory.final || '-' }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="平时" width="85" align="center">
								<template #default="{ row }">
									<span :class="getScoreClass(row.scores.theory.usual || 0)">
										{{ row.scores.theory.usual || '-' }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="总分" width="80" align="center">
								<template #default="{ row }">
									<span
										:class="getScoreClass(row.scores.theory.total || 0)"
										style="font-weight: bold"
									>
										{{ row.scores.theory.total || '-' }}
									</span>
								</template>
							</el-table-column>
						</el-table-column>

						<!-- 实践成绩部分 -->
						<el-table-column label="实践成绩" align="center">
							<el-table-column label="考试情况" width="100" align="center">
								<template #default="{ row }">
									<span :class="setStatusStyle(row.scores.practice.status)">
										{{ setStatusText(row.scores.practice.status) }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="期中" width="85" align="center">
								<template #default="{ row }">
									<span :class="getScoreClass(row.scores.practice.midTerm || 0)">
										{{ row.scores.practice.midTerm || '-' }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="期末" width="85" align="center">
								<template #default="{ row }">
									<span :class="getScoreClass(row.scores.practice.final || 0)">
										{{ row.scores.practice.final || '-' }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="平时" width="85" align="center">
								<template #default="{ row }">
									<span :class="getScoreClass(row.scores.practice.usual || 0)">
										{{ row.scores.practice.usual || '-' }}
									</span>
								</template>
							</el-table-column>

							<el-table-column label="总分" width="80" align="center">
								<template #default="{ row }">
									<span
										:class="getScoreClass(row.scores.practice.total || 0)"
										style="font-weight: bold"
									>
										{{ row.scores.practice.total || '-' }}
									</span>
								</template>
							</el-table-column>
						</el-table-column>
					</el-table>
				</div>

				<!-- 统计信息卡片 -->
				<div class="stats-container" v-if="currentSubject && statisticsItems.length > 0">
					<h3 class="stats-title">
						{{ currentExamType === 'theory' ? '理论考试统计' : '实践考试统计' }}
					</h3>

					<!-- 成绩统计卡片 -->
					<div class="stats-cards">
						<el-card
							v-for="item in statisticsItems"
							:key="item.label"
							class="stat-card"
							shadow="hover"
						>
							<div class="stat-value" :style="{ color: item.color }">{{ item.value }}</div>
							<div class="stat-label">{{ item.label }}</div>
						</el-card>
					</div>

					<!-- 考试异常情况卡片 -->
					<h3 class="stats-title" style="margin-top: 20px">考试异常情况</h3>
					<div class="stats-cards">
						<el-card
							v-for="item in examAbnormalStats"
							:key="item.label"
							class="stat-card"
							shadow="hover"
						>
							<div class="stat-value" :style="{ color: item.color }">{{ item.value }}</div>
							<div class="stat-label">{{ item.label }}</div>
						</el-card>
					</div>
				</div>
			</div>
		</el-card>
	</div>
</template>

<style scoped lang="scss">
.score-manage {
	height: 100%;
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.left-section {
			display: flex;
			align-items: center;
			gap: 5px;
		}

		.class-info {
			font-size: 14px;
			color: var(--el-text-color-regular);
			display: flex;
			align-items: center;
			gap: 10px;
		}
	}

	.operation-area {
		display: flex;
		flex-direction: column;
		gap: 15px;
		margin-bottom: 20px;
		padding: 15px;
		background-color: var(--el-fill-color-lighter);
		border-radius: 4px;

		.filter-section {
			.selector-group {
				display: flex;
				align-items: center;
				position: relative;
				gap: 20px;
				flex-wrap: wrap;

				.year-selector,
				.class-selector,
				.subject-selector,
				.exam-type-selector,
				.view-selector {
					display: flex;
					align-items: center;
					gap: 10px;

					.label {
						font-size: 14px;
						color: var(--el-text-color-regular);
					}

					.selector {
						width: 120px;
					}
				}

				.subject-selector {
					position: absolute;
					right: 0px;
				}

				.search-button {
					position: absolute;
					right: 0px;
				}

				// 班级选择器可能需要更宽一些
				.class-selector .selector {
					width: 150px;
				}
			}
		}
	}

	.chart-container {
		height: 340px;
	}

	.data-container {
		display: flex;
		gap: 20px;
		margin: 20px 0;

		.table-container {
			flex: 3;
			overflow-x: auto;
		}

		.stats-container {
			flex: 1;
			min-width: 250px;

			.stats-title {
				font-size: 16px;
				color: var(--el-text-color-primary);
				margin-bottom: 15px;
				font-weight: 500;
			}

			.stats-cards {
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				gap: 10px;

				.stat-card {
					text-align: center;
					height: 90px;
					display: flex;
					flex-direction: column;
					justify-content: center;

					.stat-value {
						font-size: 24px;
						font-weight: bold;
					}

					.stat-label {
						margin-top: 5px;
						font-size: 14px;
						color: var(--el-text-color-secondary);
					}
				}
			}
		}
	}

	.score-table {
		:deep(.el-table__header) {
			background-color: var(--el-fill-color-light);
			font-weight: bold;
		}

		.score-all {
			color: #be0bb5;
			font-weight: bold;
		}

		.score-good {
			color: #2169b1;
			font-weight: bold;
		}

		.score-medium {
			color: #067534;
		}

		.score-pass {
			color: #909399;
		}

		.score-fail {
			color: #f56c6c;
			font-weight: bold;
		}

		.status-normal {
			color: #67c23a;
		}

		.status-absent {
			color: #e6a23c;
			font-weight: bold;
		}

		.status-violation {
			color: #f56c6c;
			font-weight: bold;
		}
	}
}

// 响应式布局
@media screen and (max-width: 1200px) {
	.score-manage .data-container {
		flex-direction: column;

		.stats-container {
			width: 100%;

			.stats-cards {
				grid-template-columns: repeat(4, 1fr);
			}
		}
	}
}

@media screen and (max-width: 768px) {
	.score-manage .data-container .stats-container .stats-cards {
		grid-template-columns: repeat(2, 1fr);
	}
}
</style>
